import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { STComponent, STColumn, STChange, STRequestOptions, STData } from '@delon/abc/st';
import { SFSchema, SFDateWidgetSchema } from '@delon/form';
import { SearchDrawerService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { BasicTableComponent } from 'src/app/routes/commom';
import { TicketService } from '../../services/ticket.service';

@Component({
  selector: 'app-invoiced-list',
  templateUrl: './invoiced-list.component.html',
  styleUrls: ['../../../commom/less/commom-table.less']
})
export class InvoicedListComponent extends BasicTableComponent {
  @ViewChild('logosticsLogsModal', { static: false })
  logosticsLogsModal!: any;
  columns: STColumn[] = this.initST();
  schema: SFSchema = this.initSF();

  selectedRows: any[] = [];
  totalCallNo = 0;

  routesInfo: any = {
    mailNo: '',
    routes: []
  };

  @ViewChild('requestedModal', { static: false })
  requestedModal!: any;
  openInfo: any = { expresscompany: null, expressno: null };
  constructor(
    public service: TicketService,
    private nzModalService: NzModalService,
    private router: Router,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
  }

  search() {
    this.st?.load(1);
  }

  beforeReq = (requestOptions: STRequestOptions) => {
    Object.assign(requestOptions.body, { sts: '3' });
    if (this.sf) {
      Object.assign(requestOptions.body, {
        ...this.sf?.value,
        invoicedate: {
          start: this.sf?.value.invoicedate?.[0] || '',
          end: this.sf?.value.invoicedate?.[1] || ''
        }
      });
    }
    return requestOptions;
  };

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        this.totalCallNo = this.selectedRows.reduce((total, cv) => total + cv.vatnotax, 0).toFixed(2);
        break;
    }
  }

  deletedInvoice(item: any) {
    // if (this.selectedRows?.length <= 0) {
    //   this.service.msgSrv.warning('请选择发票');
    //   return;
    // }
    const modal = this.nzModalService.warning({
      nzTitle: '确定将所选发票作废？',
      nzCancelText: '取消',
      nzOnOk: () => {
        this.service.request(this.service.$api_delete_invoice, { id: item.id }).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('发票作废成功');
          }
          modal.destroy();
          this.st.load(1);
        });
        return false;
      }
    });
  }

  canceInvoice(item: any) {
    // if (this.selectedRows?.length <= 0) {
    //   this.service.msgSrv.warning('请选择发票');
    //   return;
    // }
    const modal = this.nzModalService.warning({
      nzTitle: '确定取消所选发票？',
      nzCancelText: '取消',
      nzOnOk: () => {
        this.service.request(this.service.$api_cancel_invoice, { id: item.id }).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('取消发票成功');
          }
          modal.destroy();
          this.st.load(1);
        });
        return false;
      }
    });
  }

  /**
   * 填写物流/修改物流
   * @param item
   */
  requestedAction(item: any) {
    this.openInfo = { expresscompany: item.expresscompany || null, expressno: item.expressno || null };
    const modal = this.nzModalService.create({
      nzTitle: item.expresscompany ? '修改物流' : '填写物流',
      nzContent: this.requestedModal,
      nzOnOk: () => {
        if (!this.openInfo?.expresscompany || !this.openInfo?.expressno) {
          this.service.msgSrv.warning('请填快递信息');
          return false;
        }
        const params = {
          expresscompany: this.openInfo.expresscompany,
          expressno: this.openInfo.expressno
        };
        this.service
          .request(this.service.$api_update_Express, {
            id: item.id,
            ...params
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success(item.expresscompany ? '修改成功' : '填写成功');
              this.st.load(1);
              modal.destroy();
            }
          });

        return false;
      }
    });
  }

  invoiceHongChong() {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择发票');
      return;
    }
    this.nzModalService.warning({
      nzTitle: '确定将所选发票红冲？',
      nzCancelText: '取消',
      nzOnOk: () => {}
    });
  }

  // 导出
  exprot() {
    this.service.exportStart({ ...this.sf?.value, pageSize: -1, sts: '3' }, this.service.$api_get_invoice_page_export);
  }

  showlogosticsLogs(item: any) {
    this.service.request(this.service.$api_get_express_routes, item.expressno).subscribe(res => {
      console.log(res);
      if (res) {
        res.routes = res.routes.map((route: any) => ({ time: route.acceptTime, value: route.remark + route.acceptAddress, color: 'gray' }));
        this.routesInfo = res;
        this.nzModalService.create({
          nzTitle: '查看物流',
          nzWidth: 600,
          nzContent: this.logosticsLogsModal,
          nzFooter: []
        });
      }
    });
  }

  private initSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        invoiceno: {
          type: 'string',
          title: '发票号码',
          ui: {
            autocomplete: 'off'
          }
        },
        invoiceno2: {
          type: 'string',
          title: '发票代码',
          ui: {
            autocomplete: 'off'
          }
        },
        vatappHCode: {
          type: 'string',
          title: '申请编号',
          ui: {
            autocomplete: 'off'
          }
        },
        invoicedate: {
          title: '开票日期',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            nzShowTime: true
          } as SFDateWidgetSchema
        },
        artoname: {
          type: 'string',
          title: '购买人',
          ui: {
            placeholder: '请输入'
          }
        },
        ltdId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getNetworkFreightForwarder({}, true)
          },
          default: ''
        },
        vatinvcode: {
          type: 'string',
          title: '分票编号',
          ui: {
            placeholder: '请输入'
          }
        },
        invoicetype: {
          type: 'string',
          title: '发票类型',
          enum: [
            { value: '', label: '全部' },
            { value: '1', label: '运输专用发票' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择'
          },
          default: ''
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      { title: '', index: 'key', type: 'checkbox' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return ((this.st.pi -1) * this.st.ps) + idx + 1 + ''
        } 
      },
      { title: '发票号码', index: 'invoiceno', width: 150 },
      { title: '发票代码', index: 'invoiceno2', width: 150 },
      {
        title: '申请编号',
        index: 'vatappHCode',
        width: 190,
        type: 'link',
        click: item =>
          this.router.navigate(['/ticket/invoice-list/detail/' + item.id], {
            queryParams: { type: 1, expressno: item.expressno }
          })
      },
      { title: '申请时间', index: 'createTime', type: 'date', width: 150 },
      { title: '发票类型', index: 'invoicetypeLabel', className: 'text-center', width: 140 },
      { title: '网络货运人', index: 'ltdName', width: 170 },
      { title: '购买人', index: 'artoname', width: 170 },
      { title: '订单数', index: 'ordlines', className: 'text-right', width: 90 },
      {
        title: '价税合计',
        index: 'vatmoney',
        width: 130,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.vatmoney }) }
      },
      {
        title: '金额',
        index: 'vatnotax',
        width: 120,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.vatnotax }) }
      },
      {
        title: '税率',
        index: 'billvatrate',
        className: 'text-right',
        width: 90,
        format: item => `${item.billvatrate ? ((item.billvatrate as number) * 100).toFixed(2) : 0}%`
      },
      {
        title: '税额',
        index: 'vattax',
        width: 120,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.vattax }) }
      },
      { title: '开票日期', index: 'invoicedate', type: 'date', width: 150 },
      {
        title: '快递信息',
        render: 'expresscompany',
        width: 180
      },
      { title: '状态', index: 'stsLabel', width: 90 },
      {
        title: '操作',
        fixed: 'right',
        className: 'text-center',
        width: 120,
        buttons: [
          { type: 'divider' },
          {
            text: '查看明细<br>',
            acl: { ability: ['TICKET-INVOICE-LIST-view'] },
            click: item =>
              this.router.navigate(['/ticket/invoice-list/detail/' + item.id], {
                queryParams: { expressno: item.expressno, type: 2, ltdId: item.shipperId }
              })
          },
          {
            text: '取消开票<br>',
            acl: { ability: ['TICKET-INVOICE-LIST-canceInvoice'] },
            click: item => this.canceInvoice(item),
            iif: item => item.sts === '1'
          },
          {
            text: '发票作废<br>',
            acl: { ability: ['TICKET-INVOICE-LIST-deletedInvoice'] },
            click: item => this.deletedInvoice(item),
            iif: item => item.sts === '3'
          },
          {
            text: '查看物流<br>',
            acl: { ability: ['TICKET-INVOICE-LIST-showExpress'] },
            click: item => this.showlogosticsLogs(item),
            iif: item => item.expresscompany
          },
          {
            text: '填写物流<br>',
            acl: { ability: ['TICKET-INVOICE-LIST-writeExpress'] },
            click: item => this.requestedAction(item),
            iif: item => !item.expresscompany
          },
          {
            text: '修改物流<br>',
            acl: { ability: ['TICKET-INVOICE-LIST-updateExpress'] },
            click: item => this.requestedAction(item),
            iif: item => item.expresscompany
          }
        ]
      }
    ];
  }
}
